<template>
  <div id="market_freegift_list">
    <div class="search-box">
      <Row type="flex" justify="space-between">
        <Row type="flex">
          <Col class="search-item"><span class="search-label">活动名称：</span><Input placeholder="请输入" v-model='activityName' :maxlength="20" @on-keyup='filterName' @on-blur="filterName"></Input></Col>
          <Col class="search-item">
            <span class="search-label">活动类型：</span>
            <Select v-model="searchObj.activityType" @on-change="search"
              style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in activityTypeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">活动状态：</span>
            <Select v-model="searchObj.status" @on-change="search"
              style="width:180px">
              <Option :value="-1">全部</Option>
              <Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="doSearch"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex">
          <Col class="search-item" style="padding-right:15px;">
            <Button v-if="exampleShow"
                  @click="exampleShow = !exampleShow">收起筛选
              <Icon type="ios-arrow-up" />
            </Button>
            <Button v-else
                    @click="exampleShow = !exampleShow">更多筛选
              <Icon type="ios-arrow-down" />
            </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example">
        <Row type="flex" justify="start" v-show="exampleShow">
          <Col class="search-item">
            <span class="search-label">门店：</span>
              <Select v-model='shopName' style="width:280px" @on-change="search" filterable multiple :max-tag-count='1' :max-tag-placeholder='maxTagPlaceholder'>
                <!-- <Option :value="-1">全部</Option> -->
                <Option v-for="item in shopList" :value="item.shopId" :key="item.value">{{ item.shopName }}</Option>
              </Select>
          </Col>
        </Row>
      </div>
      <Row type="flex" justify="end">
        <Col class="search-item" style="padding-right:15px;">
          <Dropdown trigger="click" @on-visible-change="dropVisible=!dropVisible" @on-click="skipAdd">
            <Button class="search-btn" type="primary"  v-if="hasPermission('moms:market:activitycreate')">创建
              <Icon :type="dropVisible ? 'ios-arrow-up' : 'ios-arrow-down'"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem  :name="item.value" v-for="(item, index) in activityTypeList" :key="index">{{item.label}}</DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </Col>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="tableData" :loading="loading" :height="this.tableHeight">
      <template slot-scope="{ row }" slot="activityType">
        <span>{{row.activityType === 6 ? '满赠' : row.activityType === 7 ? '满减' : row.activityType === 8 ? '折扣' : ''}}</span>
      </template>
      <template slot-scope="{ row }" slot="activityWay">
        <span>{{row.activityWay | getChannelsName}}</span>
      </template>
      <template slot-scope="{ row }" slot="activityStatus">
        <span>{{row.activityStatus == 0 ? '未开始' : row.activityStatus == 1 ? '进行中' : row.activityStatus == 2 ? '已结束' : ''}}</span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看" @click='skipDetail(row)' v-if="hasPermission('moms:market:freegiftdetail')"></i>
        <i class="iconsys iconedit" title="编辑" @click='skipEdit(row)' v-if="row.activityStatus === 0 && hasPermission('moms:market:freegiftupdate')"></i>
        <Poptip confirm title="确认删除此数据吗？" transfer @on-ok="sureDel(row)" style="text-align:left" v-if="row.activityStatus === 0 && hasPermission('moms:market:freegiftdelete')">
          <i class="iconsys icondel" title="删除"></i>
        </Poptip>
        <Poptip confirm title="确认结束此活动吗？" transfer style="text-align:left" @on-ok="skipOver(row)" v-if="row.activityStatus === 1 && hasPermission('moms:market:freegiftviewclose')">
            <i class="iconsys iconxiajia" title="立即结束"></i>
          </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="pageObj.total"
              :page-size='pageObj.pageSize'
              :current='pageObj.pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import enumsMixin from '../enums.js'
import { getShopList } from '@/api/system/store'
import { getfreeGiftList, delfreeGift, downfreeGift } from '@/api/market/freegift.js'
let that
export default {
  name: 'market_freegift_list',
  mixins: [enumsMixin],
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_freegift_list') {
        this.getData()
      }
    }
  },
  beforeCreate () {
    that = this
  },
  filters: {
    getChannelsName (value) {
      if (value) {
        let arr
        if (typeof value === 'string') {
          arr = value.split(',')
        } else {
          arr = value
        }
        return arr.map((value) => {
          const result = that.channelList.filter(item => +item['value'] === +value)
          return result[0] ? result[0]['label'] : ''
        }).join(',')
      }
      return ''
    }
  },
  data () {
    return {
      activityName: '',
      shopName: [],
      exampleShow: false,
      loading: false,
      dropVisible: false,
      searchObj: {
        activityName: '',
        activityType: -1,
        status: -1
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      shopList: [],
      columns: [
        {
          title: '活动编号',
          key: 'activityCode',
          fixed: 'left',
          width: 130
        },
        {
          title: '活动类型',
          slot: 'activityType',
          width: 100
        },
        {
          title: '活动名称',
          key: 'activityName'
        },
        {
          title: '活动开始时间',
          key: 'activityStart'
          // width: 150
        },
        {
          title: '活动结束时间',
          key: 'activityEnd'
          // width: 150
        },
        {
          title: '营销渠道',
          slot: 'activityWay'
        },
        {
          title: '活动状态',
          slot: 'activityStatus'
        },
        {
          title: '创建人',
          key: 'creator'
        },
        {
          title: '创建时间',
          key: 'createTime'
          // width: 150
        }
      ],
      tableData: [
        {

        }
      ]
    }
  },
  methods: {
    maxTagPlaceholder (num) {
      return '...'
    },
    filterName () {
      this.activityName = this.activityName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    doSearch () {
      this.searchObj.activityName = this.activityName
      this.search()
    },
    search () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    reset () {
      this.searchObj = {
        activityName: '',
        activityType: -1,
        status: -1
      }
      this.activityName = ''
      this.shopName = []
      this.pageObj.pageIndex = 1
      this.getData()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    skipAdd (type) {
      this.$router.push({ name: 'market_freegift_create', params: { type: type + '' } })
    },
    skipDetail (row) {
      this.$router.push({ name: 'market_freegift_detail', params: { id: row.activityId, type: String(row.activityType) } })
    },
    skipEdit (row) {
      this.$router.push({ name: 'market_freegift_edit', params: { id: row.activityId, type: String(row.activityType) } })
    },
    skipOver (row) {
      downfreeGift({
        merchantId: this.$store.state.user.merchantId,
        status: '2',
        itemId: row.activityId,
        modifierId: this.$store.state.user.userId,
        modifierName: this.$store.state.user.userName
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('立即结束成功！')
          this.getData()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    sureDel (row) {
      delfreeGift({
        merchantId: this.$store.state.user.merchantId,
        activityId: row.activityId
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getShopList () {
      getShopList({
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      }).then(res => {
        if (res.data.status === 200) {
          this.shopList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 满赠列表
    getData () {
      this.loading = true
      getfreeGiftList({
        // ...this.searchObj,
        activityName: this.searchObj.activityName ? this.searchObj.activityName : null,
        activityType: this.searchObj.activityType === -1 ? null : this.searchObj.activityType,
        status: this.searchObj.status === -1 ? null : this.searchObj.status,
        merchantId: this.$store.state.user.merchantId,
        // shopId: this.shopName ? (this.shopName === -1 ? null : this.shopName) : null,
        shopIds: this.shopName.length > 0 ? this.shopName : null,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount
          if (this.tableData.length > 0) {
            this.tableData = this.tableData.map(item => {
              return {
                activityCode: item.activityBase.activityCode,
                activityName: item.activityBase.activityName,
                activityType: item.activityBase.activityType,
                activityStart: item.activityBase.startTime,
                activityEnd: item.activityBase.endTime,
                activityStatus: item.activityBase.status,
                creator: item.activityBase.creatorName,
                createTime: item.activityBase.createTime,
                activityWay: item.rules[0].matchRules.channel,
                activityId: item.activityBase.activityId,
                rules: item.rules
              }
            })
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.getShopList()
    this.getData()
    if (this.hasPermission(['moms:market:freegiftupdate', 'moms:market:freegiftdetail', 'moms:market:freegiftdelete', 'moms:market:freegiftviewclose'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        fixed: 'right',
        width: 180
      })
    }
  }
}
</script>

<style lang='less'>
#market_freegift_list{
  .collection-productdesc {
    /* max-height: 38px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden; */
    /* max-width: 130px; */
  }
}
</style>
